<?php

/**
 * This is the model class for table "tbl_user".
 *
 * The followings are the available columns in table 'tbl_user':
 * @property integer $id
 * @property string $email
 * @property string $password
 * @property string $username
 * @property array $access_item
 * @property-read ApiToken[] $tokens
 * @property-read ApiToken $token last token
 */
class User extends CActiveRecord
{
	const ADMIN_NAME = 'admin';

	public $password2;

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'tbl_user';
	}

	public function __get($name)
	{
		if ($name === 'access_item') {
			$value = $this->getAttribute($name);
			if (is_string($value)) {
				$value = empty($value) ? array() : unserialize($value);
				$this->setAttribute($name, $value);
				return $value;
			}
		}
		return parent::__get($name);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		return array(
			'tokens' => array(self::HAS_MANY, 'ApiToken', 'user_id'),
			'last_token' => array(
				self::HAS_ONE, 'ApiToken', 'user_id',
				'on' => 'last_token.ip = :ip',
				'params' => array(':ip' => $_SERVER['REMOTE_ADDR']),
			),
		);
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		return array(
			array('username', 'required', 'on' => 'insert'),
			array('username', 'unique', 'on' => 'insert'),
			array('password, email', 'required'),
			array('password2', 'compare', 'compareAttribute' => 'password', 'on' => 'profile'),
			array('email', 'email'),
		);
	}

	/**
	 * Encrypt the password
	 * @param string $password
	 * @param string $salt
	 */
	public function encodePassword($password, $salt)
	{
		return md5($salt . md5($salt . $password . $salt, true) . $salt);
	}

	/**
	 * Set some attributes before save
	 */
	protected function beforeSave()
	{
		if (is_array($this->access_item)) {
			$this->access_item = serialize($this->access_item);
		}
		return parent::beforeSave();
	}

	public function attributeLabels()
	{
		return array(
			'username' => '用户名',
			'password' => '密码',
			'password2' => '确认密码',
			'email' => '电子邮件',
			'nickname' => '昵称',
			'accessItems' => '权限',
		);
	}

	public function hasAccess($project, $route = null)
	{
		if ($this->getIsAdmin()) {
			return true;
		}
		$items = $this->access_item;
		return isset($items[$project]) && ($route === null || isset($items[$project][$route]));
	}

	public function getIsAdmin()
	{
		return $this->username === self::ADMIN_NAME;
	}

	/**
	 * Returns the static model of the specified AR class.
	 * Please note that you should have this exact method in all your CActiveRecord descendants!
	 * @param string $className active record class name.
	 * @return User the static model class
	 */
	public static function model($className = __CLASS__)
	{
		return parent::model($className);
	}
}
